package ar.com.raulsanchez.syncrolist;

import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

public class ActivityEditActivity extends Activity implements OnDateSetListener, OnTimeSetListener {

    private EditText mTitulo;
    private EditText mDetalle;
    private Button mFecha;
    private Button mHora;
    private Long mId;
    private BDActividades mDbHelper;
	private Integer mUsuario_id;
	private int mActividad_id;
	private int mYear;
	private int mMonth;
	private int mDay ;
	private int mHour;
	private int mMinutes;
	private int mSeconds;
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
        mUsuario_id = new Integer(getIntent().getExtras().getInt("usuario_id"));
        mDbHelper = new BDActividades(this);
        mDbHelper.open();
        
		setContentView(R.layout.activity_edit_activity);
		
		mTitulo = (EditText) findViewById(R.id.titulo);
        mDetalle = (EditText) findViewById(R.id.detalle);
        mFecha = (Button) findViewById(R.id.button_date);
        mHora = (Button) findViewById(R.id.button_time);
        
        mId = (savedInstanceState == null) ? null
        								   : (Long) savedInstanceState.getSerializable(BDActividades.ID);
        if (mId == null && getIntent().getExtras().containsKey(BDActividades.ID)) {
        	// edit activity
            Bundle extras = getIntent().getExtras();
            mId = (extras != null) ? extras.getLong(BDActividades.ID)
                                   : null;
        }
        
        getData();
	} // onCreate

	private void getData() {
        if (mId != null) {
            Cursor actividad = mDbHelper.getActivity(mId);
            startManagingCursor(actividad);
            mTitulo.setText(actividad.getString(actividad.getColumnIndexOrThrow(BDActividades.ACTIVIDAD_TITULO)));
            mDetalle.setText(actividad.getString(actividad.getColumnIndexOrThrow(BDActividades.ACTIVIDAD_DETALLE)));
            setDateTime(actividad.getString(actividad.getColumnIndexOrThrow(BDActividades.ACTIVIDAD_FECHA)));
            mActividad_id = actividad.getInt(actividad.getColumnIndexOrThrow(BDActividades.ACTIVIDAD_ID));
        }
        else {
        	final Calendar c = Calendar.getInstance();
        	
            setDateTime(c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DAY_OF_MONTH)+" "+(c.get(Calendar.HOUR_OF_DAY)-3)+":"+c.get(Calendar.MINUTE)+":"+"00");
        }
    } // getData
	
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        saveState();
        outState.putSerializable(BDActividades.ID, mId);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        saveState();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }
    
    private void saveState() {
        String titulo  = mTitulo.getText().toString();
        String detalle = mDetalle.getText().toString();
        String fecha   = getDateTime();

        if (mId == null) {
            long id = mDbHelper.addActivity(mUsuario_id, titulo, detalle, fecha);
            if (id > 0) {
                mId = id;
            }
        } else {
            mDbHelper.updActivity(mId, mActividad_id, titulo, detalle, fecha);
        }
    }
    
    private String pad(int n) {
    	return (n>= 10) ? ""+n : "0"+n;
    } // pad
    
    public String getDateTime() {
    	/*String y  = ""+mYear;
    	String m  = (mMonth>=10)	? ""+mMonth   : "0"+mMonth;
    	String d  = (mDay>=10)		? ""+mDay	  : "0"+mDay;
    	String h  = (mHour>=10) 	? ""+mHour	  : "0"+mHour;
    	String mi = (mMinutes>=10)  ? ""+mMinutes : "0"+mMinutes;
    	String s  = (mSeconds>=10)  ? ""+mSeconds : "0"+mSeconds;*/
    	
    	return mYear+"-"+pad(mMonth)+"-"+pad(mDay)+" "+pad(mHour)+":"+pad(mMinutes)+":00";
    } // getDateTime
    
    public void setDateTime(String dt) {
    	String s[] = dt.split(" ");
    	String date[] = s[0].split("-");
    	String time[] = s[1].split(":");
    	
    	mYear    = Integer.parseInt(date[0]);
    	mMonth   = Integer.parseInt(date[1]);
    	mDay     = Integer.parseInt(date[2]);
    	mHour    = Integer.parseInt(time[0]);
    	mMinutes = Integer.parseInt(time[1]);
    	mSeconds = Integer.parseInt(time[2]);
    	
    	mFecha.setText(pad(mDay)+"/"+pad(mMonth)+"/"+pad(mYear));
    	mHora.setText(pad(mHour)+":"+pad(mMinutes));    	
    } // setDateTime
    
    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
        mYear = year;
        mMonth = month+1;
        mDay = day;
        
        setDateTime(getDateTime());   
    } // onDateSet
    
    @Override
    public void onTimeSet(TimePicker view, int hour, int minute) {
        mHour = hour;
        mMinutes = minute;
        
        setDateTime(getDateTime());   
    } // onTimeSet
    
	// EVENTO DATE EDIT
	public void dateEdit(View view) {
		DatePickerFragment datePicker = new DatePickerFragment();
		datePicker.setDate(mYear, mMonth, mDay);
	    datePicker.show(getFragmentManager(), "datePicker");
	} // dateEdit
	
	// EVENTO TIME EDIT
	public void timeEdit(View view) {
		TimePickerFragment timePicker = new TimePickerFragment();
		timePicker.setTime(mHour, mMinutes, mSeconds);
	    timePicker.show(getFragmentManager(), "timePicker");
	} //timeEdit
	
	// EVENTO ACCEPT
	public void accept(View view) {
		Intent returnIntent = new Intent();
		//returnIntent.putExtra("result" ,result);
		setResult(RESULT_OK,returnIntent);     
		finish();
	} // accept
	
	// EVENTO CANCEL
	public void cancel(View view) {
		Intent returnIntent = new Intent();
		setResult(RESULT_CANCELED,returnIntent);     
		finish();
	} // cancel
}
